<?php 
/**
 * Phone Collection Application Platform Faulty Product Controller 
 * this Controller mainly for warehoue to check the RMA bring back by he driver 
 * there are 3 major fucntion for RMA system 
 * 
 * 1. gather RMA and handling it 
 * 2. give sumary and notice of the RMA result
 * 3. record and following up the RMA life cycle , untile the credit is finally give or dispose
 * 
 * @package  
 * @category Controller
 * @author   Norman Dong <eco1@phonecollection.com.au>
 * @version  Initial
 * @copyright www.phonecollection.com.au
 * @link     www.phonecollection.com.au
 * @license  Commercial
 */
class FaultyauditController extends Zend_Controller_Action
{
	//Faulty Code PreFix
	const PREFIX_FAULTY_REJECT = "FRJ";
	const PREFIX_FAULTY_DISPOSE = "FDP";
	const PREFIX_FAULTY_RETURNCHINA = "FCN";
	const PREFIX_FAULTY_RETURNSUPPLY = "FSU";
	const PREFIX_FAULTY_SALEONLINE = "FSL";
	
	//Faulty Code 
	const FAULTY_STATUS_DISPOSE = 300;
	const FAULTY_STATUS_RSLIST = 41;
	const FAULTY_STATUS_RSRMA = 42;
	const FAULTY_STATUS_RSCREDIT = 43;
	
	const FAULTY_STATUS_RETURNSUPPLY = 400;
	const FAULTY_STATUS_RETURNCHINA = 500;
	const FAULTY_STATUS_SALEONLINE = 600;
	
	
    public function init(){
    /**
	 *
	 *
	 */    
	
	}
	
	public function summaryAction(){
	
	
	}
	
	/**
	 * this is the entry page of RMA audit 
	 * it shows how many "unhandled" RMA in the sytem 
	 * it also able to reset rma  if any mistakes has been made 
	 */

    public function indexAction(){
	
	$this->view->title = " Online RMA Auditing System";
    $this->view->headTitle($this->view->title, 'PREPEND');
    $faulty_product = new Model_DbTable_Faultyproduct();
        
    $this->view->count_bspc = count($faulty_product->listAllUnhandledFaultyByShop("BSPC"));
    $this->view->count_bhpc = count($faulty_product->listAllUnhandledFaultyByShop("BHPC"));
    $this->view->count_bbpc = count($faulty_product->listAllUnhandledFaultyByShop("BBPC"));
    $this->view->count_copc = count($faulty_product->listAllUnhandledFaultyByShop("COPC"));
    $this->view->count_cbpc = count($faulty_product->listAllUnhandledFaultyByShop("CBPC"));
    $this->view->count_eppc = count($faulty_product->listAllUnhandledFaultyByShop("EPPC"));
    $this->view->count_fgpc = count($faulty_product->listAllUnhandledFaultyByShop("FGPC"));
    $this->view->count_hppc = count($faulty_product->listAllUnhandledFaultyByShop("HPPC"));
    $this->view->count_kcpc = count($faulty_product->listAllUnhandledFaultyByShop("KCPC"));
    $this->view->count_nlpc = count($faulty_product->listAllUnhandledFaultyByShop("NLPC"));
    $this->view->count_pmpc = count($faulty_product->listAllUnhandledFaultyByShop("PMPC"));
    $this->view->count_wbpc = count($faulty_product->listAllUnhandledFaultyByShop("WBPC"));
    $this->view->count_bsic = count($faulty_product->listAllUnhandledFaultyByShop("BSIC"));
    $this->view->count_slic = count($faulty_product->listAllUnhandledFaultyByShop("SLIC"));
    $this->view->count_wgic = count($faulty_product->listAllUnhandledFaultyByShop("WGIC"));
    $this->view->count_wbic = count($faulty_product->listAllUnhandledFaultyByShop("WBIC"));
    $this->view->count_adpc = count($faulty_product->listAllUnhandledFaultyByShop("ADPC"));
    $this->view->count_clpc = count($faulty_product->listAllUnhandledFaultyByShop("CLPC"));
    $this->view->count_wlic = count($faulty_product->listAllUnhandledFaultyByShop("WLIC"));
	$this->view->count_wgpc = count($faulty_product->listAllUnhandledFaultyByShop("WGPC"));
    //$this->view->count_bhpc = count($faulty_product->listAllUnhandledFaultyByShop("BHPC"));
    
    if($_POST){
    	
    	$faulty_product->resetAudit($_POST['id_rma']);
    	echo '<script language = "javascript">alert("It is Done;");</script>';
    }
	
    }
    /**
     * this is the page to show the list to handling for a shop
     * if rma is handled it disappeared
     */
    public function auditAction(){
    	
    $shopHead = $this->_getParam('shop');
    $this->view->shophead = $shopHead;
    $faulty_product = new Model_DbTable_Faultyproduct();
    $this->view->faultyproducts = $faulty_product->listAllUnhandledFaultyByShop($shopHead);
    
    //d($this->view->faultyproducts);
    
    }    
    /**
     * This function is updated by leo
     * this is the mean function that submit the rma result 
     * it will save the status in the table and send email 
     * notification when reject 
     * it also handling the repair parts rma and add stock back to the shop
     * 
     *@author Leo
     *Update updateaudit for automatical add stock when cancel parts
     *@version 2014-06-20
     *
     */
    
    public function updateauditAction(){
    	
    //var_dump($_POST);
    $faulty_product = new Model_DbTable_Faultyproduct();
    $recShopList = unserialize(ARR_RCENTER_MAPPING);
    $prstock = new Model_DbTable_Pr_Prstock();
    $prstockmove = new Model_DbTable_Pr_Prstockmovement();
    $movecode = new Model_DbTable_Pr_Prstockmovecode();
    $productsdetail = new Model_DbTable_Pr_Prproducts();
    $ram = new Model_DbTable_Faultyproduct();
    $mail = new Model_Emailshandler();
    $ramId = $_POST['id_faulty'];
    $fReason = $ram->getFaultyProduct($ramId);
    $productv1 = new Model_DbTable_Productsva();
    $mailAdd = 'office5@phonecollection.com.au';
    
    
    if(isset($_POST['audit_faulty']) and isset($_POST['audit_handle'])){
    	
    	if($_POST['audit_faulty']==2 && trim($_POST['audit_comment']) == '' ){

    		echo "<h1>if you reject a RMA, Please provide clear reason of reject in comment to the shop,record will not saved,go back and try again</h1>";
    		
    	}
    	else{
    		

    $idFaulty = $_POST['id_faulty'];    
    $auditFaulty = $_POST['audit_faulty'];
    $auditComment = $_POST['audit_comment'];
    $auditHandle = $_POST['audit_handle'];
    $aduitSupplier = NULL;
    
    $auditSupplier = $_POST['audit_supplier'];
    $auditSupplier2 = $_POST['audit_supplier2'];
    
    if( $auditFaulty == 1 && $auditHandle ==4 ){
    	$auditSupplier = $_POST['audit_supplier'];
    }
    
    if( $auditFaulty == 2 && $auditHandle ==4 ){
    	$auditSupplier = $_POST['audit_supplier2'];
    }
    if($_POST['check_box']&& $auditFaulty == 2&& $fReason['reason_faulty'] >= 40001){
    	$barcode = $_POST['productfaultcode'];
    	$idFaultProduct = $productsdetail->getProductID($barcode);
    	$fshopId = $_POST['shophead'];
    	$staffName = $_POST['staffname'];

    	$recId = $recShopList[$fshopId];
    	
    	$spStock = $prstock->getShopStock($idFaultProduct, $recId);
    	$qty = $_POST['faultqty'];
    	$fixQty = $spStock + $qty;
    	$prstock->updateStockShop($idFaultProduct, $fixQty, $recId);
    	$prstockmove->addMovement(7, $idFaultProduct, $qty, 'Yuki', $recId,'RMA'.$ramId,$auditComment);
    	
    	$shopheads = new Model_DbTable_Shoplocation();
    	 
    	$shopList = $shopheads->getNameByHead(trim($_POST['shophead']));
    	$shopEmail = $shopList['shop_email'];
    	$mail->sendNormalEmail($shopEmail, 'The item '.$barcode.' has been canceled and stock has added', 'The RMAID:'.$idFaulty);
    	
    }
    if($auditFaulty == 3 && $auditHandle == 1 && $fReason['reason_faulty'] >= 40001 && $fReason['reason_faulty'] < 99999){
    	$barcode = $_POST['productfaultcode'];
    	$idFaultProduct = $productsdetail->getProductID($barcode);
    	$fshopId = $_POST['shophead'];
    	$staffName = $_POST['staffname'];
    
    
    	$recId = $recShopList[$fshopId];

    	$spStock = $prstock->getShopStock($idFaultProduct, $recId);
    	$qty = $_POST['faultqty'];
    	$fixQty = $spStock + $qty;
    	$prstock->updateStockShop($idFaultProduct, $fixQty, $recId);
    	$prstockmove->addMovement(7, $idFaultProduct, $qty, 'Yuki', $recId,'RMA'.$ramId,$auditComment);
    	//alert('The stock has been added');
   
    	$shopheads = new Model_DbTable_Shoplocation();
    	
    	$shopList = $shopheads->getNameByHead(trim($_POST['shophead']));
    	$shopEmail = $shopList['shop_email'];
    	$mail->sendNormalEmail($mailAdd, 'The item '.$barcode.' has been canceled and stock has added', 'The RMAID:'.$idFaulty);
    	$mail->sendNormalEmail($shopEmail, 'The item '.$barcode.' has been canceled and stock has added', 'The RMAID:'.$idFaulty);
    }
    if($auditFaulty == 1 && $auditHandle == 9){
    	$barcode = $_POST['productfaultcode'];
    	$idFaultProduct = $productsdetail->getProductID($barcode);
    	$fshopId = $_POST['shophead'];
    
    	
    	$shopheads = new Model_DbTable_Shoplocation();
    	 
    	$shopList = $shopheads->getNameByHead(trim($_POST['shophead']));
    	$shopEmail = $shopList['shop_email'];
    	$mail->sendNormalEmail($mailAdd, 'The RMA ID:'.$idFaulty.'(item:'.$barcode.')'.' has been Received , However,it is Physical Damaged parts', 'The RMAID:'.$idFaulty.'('.$barcode.')'.'<br/>'
    			.'However, base on checking and examination, We consider it was Physical Damaged By Technician During Repairing.'.'<br/>'.'Please call Yuki if you have any questions');
    	$mail->sendNormalEmail($shopEmail, 'The RMA ID:'.$idFaulty.'(item:'.$barcode.')'.' has been Received , However,it is Physical Damaged parts', 'The RMAID:'.$idFaulty.'('.$barcode.')'.'<br/>'
    			.'However, base on checking and examination, We consider it was Physical Damaged By Technician During Repairing.'.'<br/>'.'Please call Yuki if you have any questions');
    	
    	
    }
    
    //2014-07-24 Leo
    //If the barcode is wrong, for input and update correct barcode into database
    if($fReason['reason_faulty'] < 40000){
   		 if($_POST['correct_barcode']!=null && $auditHandle == 3 && $auditFaulty == 2 || $_POST['correct_barcode']!=null && $auditHandle == 4 && $auditFaulty == 2 || $_POST['correct_barcode']!=null && $auditHandle == 5 && $auditFaulty == 2){

        		$productCode = $_POST['correct_barcode'];//correct barcode
        		$productId = $productv1->getProductID(trim($productCode));//get id
        		$productTitel = $productv1->getProduct($productId);//get product detail
        	if($productId!=null){
        		$faulty_product->updateFaultyProductCodeTitle($idFaulty, $productCode, $productTitel['title_product']);
        	}else{
        		return false;
        	}
   		 }
    }
   
    $faulty_product->auditFaultyProduct($idFaulty, $auditFaulty, $auditComment,$auditHandle,$auditSupplier);
    
    $shopheads = new Model_DbTable_Shoplocation();
    $shopList = $shopheads->getNameByHead(trim($_POST['shophead']));
    $shopEmail = $shopList['shop_email'];
    $managerEmail = $shopList['shop_manager_email'];
    
    $rmaEmail = new Model_Rmaemailshandler();
    	if($auditFaulty == 2){
    		
    		
    		$rmaEmail->rmaRejectedemail($idFaulty, $shopEmail, $managerEmail,$auditComment,trim($_POST['shophead']));
    	}
    	if($auditFaulty == 2 && $_POST['send_photo']){
    		$barcode = $_POST['productfaultcode'];
    		$mail->sendAttachEmail($mailAdd, 'PHOTO OF RMA ID:'.$idFaulty.'(item:'.$barcode.')', $auditComment, getcwd()."/im/RMA_image/",$idFaulty.".jpg");
    		$mail->sendAttachEmail($shopEmail, 'PHOTO OF RMA ID:'.$idFaulty.'(item:'.$barcode.')', $auditComment, getcwd()."/im/RMA_image/",$idFaulty.".jpg");
    	}	   	
    }	
    }
    	
    else{//save the comment only 
    	$idFaulty = $_POST['id_faulty'];
    	$auditComment = $_POST['audit_comment'];
    	
    	$faulty_product->updateComment($idFaulty, $auditComment);
    }
    if($_POST['audit_faulty']==2 && trim($_POST['audit_comment']) == '' ){
    	
    }
    else{
    	$this->_redirect("/faultyaudit/audit/shop/".$_POST['shophead']);
    }
    
    }

    /**
     * this is one of the sumary function to show from time to time 
     * the top faulty barcode
     * this function has not be in good news
     */
	public function topfaultybarcodeAction(){
		
		$fProduct = new Model_DbTable_Faultyproduct();
		
		if($_POST){
			$dateBegin = $_POST['date_begin'];
			$dateEnd = $_POST['date_end'];
			$topNum = $_POST['topnum'];
			$this->view->topnum = $topNum;
			
			$this->view->fproducts = $fProduct->listFaultyProductByDate($dateBegin,$dateEnd);		
			
			
		}
		else{
			
			echo "Error Occur, Please Submit From Summary Page";
		}
	}
	/**
	 * also one of the summary function to find out the top REJECTED barcode for time period
	 */
	public function toprejectbarcodeAction(){
	
		$fProduct = new Model_DbTable_Faultyproduct();
	
		if($_POST){
			$dateBegin = $_POST['date_begin'];
			$dateEnd = $_POST['date_end'];
			$topNum = $_POST['topnum'];
			$this->view->topnum = $topNum;
				
			$this->view->fproducts = $fProduct->listRejectFaultyByDate($dateBegin, $dateEnd);
				
				
		}
		else{
				
			echo "Error Occur, Please Submit From Summary Page";
		}
	}
	/**
	 * Summary function , which shop return more rma
	 */
	public function topfaultyshopAction(){
	
		$fProduct = new Model_DbTable_Faultyproduct();
	
		if($_POST){
			$dateBegin = $_POST['date_begin'];
			$dateEnd = $_POST['date_end'];
			//$topNum = $_POST['topnum'];
			//$this->view->topnum = $topNum;
				
			$this->view->fproducts = $fProduct->listFaultyShopByDate($dateBegin,$dateEnd);
				
				
		}
		else{
				
			echo "Error Occur, Please Submit From Summary Page";
		}
	}
	/**
	 * summary function , which shop rma been reject most 
	 */
	public function toprejectshopAction(){
	
		$fProduct = new Model_DbTable_Faultyproduct();
	
		if($_POST){
			$dateBegin = $_POST['date_begin'];
			$dateEnd = $_POST['date_end'];
			//$topNum = $_POST['topnum'];
			//$this->view->topnum = $topNum;
	
			$this->view->fproducts = $fProduct->listRejectShopByDate($dateBegin, $dateEnd);
	
	
		}
		else{
	
			echo "Error Occur, Please Submit From Summary Page";
		}
	}
	
	/**
	 * a summary page to show individual barcode faulty summary
	 */
	public function faultybarcodedetailAction(){
	
	$productCode = trim($_GET['product_code']);
	$dateBegin =  trim($_GET['date_begin']);
	$dateEnd = trim($_GET['date_end']);
	
	$fProduct = new Model_DbTable_Faultyproduct();
	$this->view->fproductrow = $fProduct->singleBarCodeFaultyDetail($productCode, $dateBegin, $dateEnd);
	
	}
	/**
	 * a summary page to show the shop RMA details 
	 */
	public function faultyshopdetailAction(){
		$shopCode = trim($_GET['shop_code']);
		$dateBegin =  trim($_GET['date_begin']);
		$dateEnd = trim($_GET['date_end']);
		
		$fProduct = new Model_DbTable_Faultyproduct();
		$this->view->fproductrow = $fProduct->singleShopFaultyDetail($shopCode, $dateBegin, $dateEnd);		
	}
	/**
	 * Export all accept faulty into a KA list 
	 */
	public function exportresultAction(){
		
		//generate the start date and End date 
		//choose shop 
		$fProduct = new Model_DbTable_Faultyproduct();
		$product = new Model_DbTable_Productsva();
		$prProduct = new Model_DbTable_Pr_Prproducts();
		
		$arrFileHeader = array("<SCODE>","<DESC>","<LOC>","<C_QTY>","<ADJ_QTY>","<STAFF>");
		
		if($_POST){
		$afterFix= rand(100,999);
			
		$resultRow = $fProduct->getAuditResult($_POST['date_begin'], $_POST['date_end']);
		//var_dump($resultRow);
			//create file 	
		$fileName = "AEX".trim($_POST['date_begin'])."-".trim($_POST['date_end']).$afterFix.".csv";
		$fl=fopen(getcwd()."/rmaexport/".$fileName,"w");
		fputcsv($fl,$arrFileHeader);

		
		foreach($resultRow as $key => $value){
			$tmpArr = array();
			
			
			$tmpArr[0] = trim(strtoupper($value['product_code_faulty']));
			$productDetail = $product->getProductNameByCode(trim(strtoupper($value['product_code_faulty'])));
			if($productDetail){
				$tmpArr[1] = $productDetail;
			}else{
				$prProductDetail = $prProduct->getProductByCode($value['product_code_faulty']);
				$tmpArr[1] = $prProductDetail['title_product'];
			}
			$tmpArr[2] = $value['shopcode_faulty'];
			$tmpArr[3] = " ";
			$tmpArr[4] = "-".$value["SUM(`faulty_qty`)"].".000";//Qty
			$tmpArr[5] = $value['staff_name_faulty'];
			
			fputcsv($fl, $tmpArr);
			
		}
		fclose($fl);
		
		}
	
	}
	
	//
	/**
	 * in the RMA life cycle step 2  Reject  2  to 200  only one step 
	 * if rejected print it out and return to show 
	 */
	public function printRejectListAction(){
		
		$faultyProduct = new Model_DbTable_Faultyproduct();
		$this->view->rejectList = $faultyProduct->listAllRejectInitial();
	
	}
	/**
	 * if the rejecttion list has been printed out 
	 * then this rma is finally handdled , it disappear 
	 */
	public function saveRejectListAction(){
		
		
		date_default_timezone_set('Australia/Melbourne');
		$dateToday = Model_DatetimeHelper::dateToday();
		$faultyProduct = new Model_DbTable_Faultyproduct();
		$faultyStatusRecord = new Model_DbTable_Faulty_Status();
		
		$randNo = rand(1,9);
		
		$remark = self::PREFIX_FAULTY_REJECT.$dateToday.$randNo;
		
		if($_POST){
			
			foreach($_POST["arr_action"] as $k => $v){
				//update status
				echo $v;
				echo $_POST['faulty_handle'];
				//$faultyProduct->updateFaultyHandleStatus($v,200);
				
				//record 
				$faultyStatusRecord->addRecord($v,$_POST['faulty_handle'], $dateToday,$_POST["staff_name"], $remark);
				
			}
			
		}
		
	}
	//
	/**
	 *Dispose 3 to 300 only one step
	 *print and sign dispost list , after check the item is then dumped 
	 */
	public function printDisposeListAction(){
		
		$faultyProduct = new Model_DbTable_Faultyproduct();
		$this->view->disposeList = $faultyProduct->listAllDisposeInitial();
		//echo self::FAULTY_STATUS_DISPOSE;
	}
	
	/**
	 * this is the actually function to choose all the dump list 
	 * save it and then disappear in the list , case is consider close
	 */
	public function saveDisposeListAction(){
		
		date_default_timezone_set('Australia/Melbourne');
		$dateToday = Model_DatetimeHelper::dateToday();
		$faultyProduct = new Model_DbTable_Faultyproduct();
		$faultyStatusRecord = new Model_DbTable_Faulty_Status();
		$randNo = rand(1,9);
		//$tmpId = $this->FAULTY_STATUS_DISPOSE;
		$remark = self::PREFIX_FAULTY_DISPOSE.$dateToday.$randNo;
		
		if($_POST){
				
			foreach($_POST["arr_action"] as $k => $v){
				$faultyProduct->updateFaultyHandleStatus($v,self::FAULTY_STATUS_DISPOSE);
				//record
				$faultyStatusRecord->addRecord($v,self::FAULTY_STATUS_DISPOSE,$dateToday,$_POST["staff_name"], $remark);
			}
				
		}				
		$this->view->fdpNo = $remark;
		$this->view->date = $dateToday;
	}

	/**
	 * this is for print the list return to china
	 * when list is printed , the case is consider handdled
	 * Return 4 to 400 only one step 
	 * currently , we don't care how china handling the rma
	 */
	public function printReturnChinaAction(){
		$faultyProduct = new Model_DbTable_Faultyproduct();
		$this->view->chinaList = $faultyProduct->listAllReturnChinaInitial();
	}
	/**
	 * after saveing he return to china , case close
	 */
	public function saveReturnChinaAction(){
		
		date_default_timezone_set('Australia/Melbourne');
		$dateToday = Model_DatetimeHelper::dateToday();
		$faultyProduct = new Model_DbTable_Faultyproduct();
		$faultyStatusRecord = new Model_DbTable_Faulty_Status();
		$randNo = rand(1,9);
		//$tmpId = $this->FAULTY_STATUS_DISPOSE;
		$remark = self::PREFIX_FAULTY_RETURNCHINA.$dateToday.$randNo;	

		if($_POST){
		
			foreach($_POST["arr_action"] as $k => $v){
				$faultyProduct->updateFaultyHandleStatus($v,self::FAULTY_STATUS_RETURNCHINA);
				//record
				$faultyStatusRecord->addRecord($v,self::FAULTY_STATUS_RETURNCHINA,$dateToday,$_POST["staff_name"], $remark);
			}
		
		}
		$this->view->fcnNo = $remark;
		$this->view->date = $dateToday;		
	}
	/**
	 *transfer to Online 
	 *this is the function was used before , but no longer in use 
	 */

	public function printTransferOnlineAction(){
		$faultyProduct = new Model_DbTable_Faultyproduct();
		$this->view->saleList = $faultyProduct->listAllSaleOtherInitial();
	}
	/**
	 *transfer to Online
	 *this is the function was used before , but no longer in use
	 */
	public function saveTransferOnlineAction(){
		
		date_default_timezone_set('Australia/Melbourne');
		$dateToday = Model_DatetimeHelper::dateToday();
		$faultyProduct = new Model_DbTable_Faultyproduct();
		$faultyStatusRecord = new Model_DbTable_Faulty_Status();
		$randNo = rand(1,9);
		//$tmpId = $this->FAULTY_STATUS_DISPOSE;
		$remark = self::PREFIX_FAULTY_SALEONLINE.$dateToday.$randNo;
		
		if($_POST){
		
			foreach($_POST["arr_action"] as $k => $v){
				$faultyProduct->updateFaultyHandleStatus($v,self::FAULTY_STATUS_SALEONLINE);
				//record
				$faultyStatusRecord->addRecord($v,self::FAULTY_STATUS_SALEONLINE,$dateToday,$_POST["staff_name"], $remark);
			}
		
		}
		$this->view->fslNo = $remark;
		$this->view->date = $dateToday;		
		
	}
	/**
	 * return to supplier function is more complex then others
	 * because after we return the item back to supplier 
	 * we need to record 
	 * when the item shiped
	 * if the supplier received
	 * if the credit allocated
	 * this is the step one of return to supplier 
	 * 
	 */
	public function printReturnSupplierAction(){
		
		//choose supplier ,print list 
		$faultyProduct = new Model_DbTable_Faultyproduct();
		if($_GET["spid"]==""){
			$this->view->supplierList = $faultyProduct->listAllReturnSupplyInitial();
		}
		else{
			$this->view->supplierList = $faultyProduct->listStatusBySupplier(4,$_GET["spid"]);
		}
		//list choose seal box
	}
	/**
	 * This means flora gather all the list 
	 * collect enough in the box 
	 * give a list and also email to elain
	 * change status to 51
	 * if kept 51 by 2 days , send email to flora 
	 */
	public function saveReturnSupplierAction(){
		// This means flora gather all the list 
		// collect enough in the box 
		//give a list and also email to elain
		//change status to 51
		//if kept 51 by 2 days , send email to flora 
		date_default_timezone_set('Australia/Melbourne');
		$dateToday = Model_DatetimeHelper::dateToday();
		$faultyProduct = new Model_DbTable_Faultyproduct();
		$faultyStatusRecord = new Model_DbTable_Faulty_Status();
		$randNo = rand(1,9);
		//$tmpId = $this->FAULTY_STATUS_DISPOSE;
		$remark = self::PREFIX_FAULTY_RETURNSUPPLY.$dateToday.$randNo;
		
		if($_POST){
		
			foreach($_POST["arr_action"] as $k => $v){
				$faultyProduct->updateFaultyHandleStatus($v,self::FAULTY_STATUS_RSLIST);
				//record
				$faultyStatusRecord->addRecord($v,self::FAULTY_STATUS_RSLIST,$dateToday,$_POST["staff_name"], $remark);
			}
		
		}
		$this->view->fslNo = $remark;
		$this->view->date = $dateToday;
		
	}
	
	/**
	 * submit rma is the display page to return to supplier 
	 */
	public function submitRmaAction(){
		//see the list  , do online or call 
		//fill in rma no , if no rma number use the one created 
		$faultyProduct = new Model_DbTable_Faultyproduct();
		if($_GET["spid"]==""){
			$this->view->supplierList = $faultyProduct->listAllReturnSupplyRma();
		}
		else{
			$this->view->supplierList = $faultyProduct->listStatusBySupplier(41,$_GET["spid"]);
		}
		//list choose seal box
		
		
	}
	/**
	 * after selection of the product , it consider begin to return to the supplier 
	 */
	public function saveSubmitRmaAction(){
		
		date_default_timezone_set('Australia/Melbourne');
		$dateToday = Model_DatetimeHelper::dateToday();
		$faultyProduct = new Model_DbTable_Faultyproduct();
		$faultyStatusRecord = new Model_DbTable_Faulty_Status();
		$randNo = rand(1,9);
		//$tmpId = $this->FAULTY_STATUS_DISPOSE;
		$remark = self::PREFIX_FAULTY_RETURNSUPPLY.$dateToday.$randNo;
		
		if($_POST){
		
			foreach($_POST["arr_action"] as $k => $v){
				$faultyProduct->updateFaultyHandleStatus($v,self::FAULTY_STATUS_RSRMA);
				$lastRemark =$faultyStatusRecord->getLastRecord($v); 
				//record
				$faultyStatusRecord->addRecord($v,self::FAULTY_STATUS_RSRMA,$dateToday,$_POST["staff_name"],$lastRemark["remark_status"],$_POST["rma_no"]);
			}
		
		}
		$this->view->fslNo = $remark;
		$this->view->date = $dateToday;
		//
	}
	
	/**
	 * after gather the list , the rma is packed and post back to supplier 
	 * tracking no will be add at this moment 
	 */
	public function postBackAction(){

		$faultyProduct = new Model_DbTable_Faultyproduct();
		if($_GET["spid"]==""){
			$this->view->supplierList = $faultyProduct->listAllReturnSupplyPostback();
		}
		else{
			$this->view->supplierList = $faultyProduct->listStatusBySupplier(42,$_GET["spid"]);
		}
		
		
	}
	/**
	 * this is the function which actually do the action 
	 */
	public function savePostBackAction(){
		
		date_default_timezone_set('Australia/Melbourne');
		$dateToday = Model_DatetimeHelper::dateToday();
		$faultyProduct = new Model_DbTable_Faultyproduct();
		$faultyStatusRecord = new Model_DbTable_Faulty_Status();
		$randNo = rand(1,9);
		//$tmpId = $this->FAULTY_STATUS_DISPOSE;
		$remark = self::PREFIX_FAULTY_RETURNSUPPLY.$dateToday.$randNo;
		
		if($_POST){
		
			foreach($_POST["arr_action"] as $k => $v){
				$faultyProduct->updateFaultyHandleStatus($v,self::FAULTY_STATUS_RSCREDIT);
				//record
				$lastRemark =$faultyStatusRecord->getLastRecord($v);
				$faultyStatusRecord->addRecord($v,self::FAULTY_STATUS_RSCREDIT,$dateToday,$_POST["staff_name"],$lastRemark["remark_status"],NULL,$_POST["tracking_no"]."[".$_POST["ship_method"]."]");
			}
		
			
			$mail = new Model_Rmaemailshandler();
			$mail->faultySendBackEmail($_POST["ship_method"]);
		}
		$this->view->fslNo = $remark;
		$this->view->date = $dateToday;		
		
		
		
	}
	/**
	 * after post back it is account department to keep looking for the credit 
	 * this is the list that waiting for it 
	 */
	public function listWaitCreditAction(){
		$faultyProduct = new Model_DbTable_Faultyproduct();
		if($_GET["spid"]==""){
			$this->view->supplierList = $faultyProduct->listAllReturnSupplyWaitCredit();
		}
		else{
			$this->view->supplierList = $faultyProduct->listStatusBySupplier(43,$_GET["spid"]);
		}		
		
	}
	/**
	 * this is the actual page to save the credit note into the system
	 * at here the rma lifecycle consider done 
	 * but this one is not in good use
	 */
	public function saveCreditReceivedAction(){
		
		date_default_timezone_set('Australia/Melbourne');
		$dateToday = Model_DatetimeHelper::dateToday();
		$faultyProduct = new Model_DbTable_Faultyproduct();
		$faultyStatusRecord = new Model_DbTable_Faulty_Status();
		$randNo = rand(1,9);
		//$tmpId = $this->FAULTY_STATUS_DISPOSE;
		$remark = self::PREFIX_FAULTY_RETURNSUPPLY.$dateToday.$randNo;
		
		if($_POST){
		
			foreach($_POST["arr_action"] as $k => $v){
				$faultyProduct->updateFaultyHandleStatus($v,self::FAULTY_STATUS_RETURNSUPPLY);
				//record
				$lastRemark =$faultyStatusRecord->getLastRecord($v);
				$faultyStatusRecord->addRecord($v,self::FAULTY_STATUS_RETURNSUPPLY,$dateToday,$_POST["staff_name"],$remark,NULL,NULL,$_POST["credit_note"]);
			}
		
		}
		$this->view->fslNo = $remark;
		$this->view->date = $dateToday;		
		
		
	}
	
	/**
	 * this is the entry page to tracking the rma lifecycle
	 */
	
	public function faultyStatusAction(){
		
		
	}
	/**
	 * this is the function to check the final status of given rma product code 
	 * this function is not in use
	 */
	
	public function listFinalStatusAction(){
		$stHead = $this->_getParam("code");
		$fStatus = new Model_DbTable_Faulty_Status();
		$this->view->list = $fStatus->listByStatusHead($stHead);
		
	}
	/**
	 * this is the function to check the final status of given rma product code
	 * this function is not in use
	 */
	public function listStatusDetailAction(){
		
		$stHead = $this->_getParam("code");
		$fStatus = new Model_DbTable_Faulty_Status();
		$this->view->list = $fStatus->listByStatusHead($stHead,true);		
		
	}
	
	/**
	 * this is the function to check the final status of given rma product code
	 * this function is not in use
	 */
	public function checkReturnSupplyConditionAction(){
		$cond = trim($_GET["cond"]);
		if($cond==4){
			//check every 2 weeks 
			
			
		}
		if($cond==41){
			//flora gathered the products need to give to elain
			//get all last status is 51
			//check if any date last two days
			//if yest send email to flora
		}

		if($cond==42){
			//recieve the case not do the online staff
			//get all last status is 52
			//check if any date last 3 days
			//if yest send email to flora
		}		
		
		if($cond==43){
			//online rma done, need to ship out
			//remark the tracking no 
			//give 5 days 
		}
		
	}
	//
	/**
	 * This is for check supplier faulty rate , this function is added in the middle of 
	 * 2014 this function is not in good use
	 * @author Norman 20140701 
	 * Supplier's  Faulty Rate Summary , China is One Supplier 
	 */
	
	public function supplierFaultyRateAction(){
		
		$arrShop = unserialize(ARR_SHOP);
		$arrIDSupplier = array(34,36,38,39);
		
		
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		$mySupplier = $this->_getParam("supplier");
		$myPart = $this->_getParam("id");
		
		
		if(isset($_POST['submit'])){
			if($_POST['end_date']!= null && $_POST['start_date'] != null)
			$dateBegin = $_POST['start_date'];
			$dateEnd = $_POST['end_date'];
			$this->_redirect("/faultyaudit/supplier-faulty-rate/date_begin/".$dateBegin."/date_end/".$dateEnd);
		}
		
		$shop = "";
		
		
		
		$faulty = new Model_DbTable_Faultyproduct();
		
		$arrRes = array();
		$arrSupplier = array();
		$arrParts = array();
		$arrShopCode = array();
		
		foreach ($arrIDSupplier as $idSupplier ){
			
			$list = $faulty->listAllAcceptReturnToSupplier($dateBegin, $dateEnd, $idSupplier);
			
			foreach($list as $key => $v){
				
				$arrRes[$key] = $v;
				$arrSupplier[$key] = $v['audit_supplier'];
				$arrParts[$key] = $v['product_code_faulty'];
				$arrShopCode[$key] = $v['shopcode_faulty'];
			}
			
		}
		
		$list2 = $faulty->listAllAcceptReturnToChina($dateBegin, $dateEnd);
	
		foreach($list2 as $key => $v){
		
			$arrRes[] = $v;
			$arrSupplier[] = 99;
			$arrParts[] = $v['product_code_faulty'];
			$arrShopCode[] = $v['shopcode_faulty'];
		}
		array_multisort($arrSupplier,SORT_ASC,$arrParts,SORT_ASC,$arrShopCode,SORT_ASC,$arrRes);

		//d($arrRes);
		
		//d($arrSupplier);
		
		$arrFinalRes = array();
		
		foreach($arrRes as $key => $v){
			$supplier = 99;
			if(trim($v['audit_supplier'])!=""){
				$supplier = $v['audit_supplier']; 
			}

			$arrFinalRes[$supplier][$v['product_code_faulty']][] = array($v['shopcode_faulty'],$v['date_faulty'],$v['staff_name_faulty'],$v['comment_faulty']);	
			
		}
		foreach($arrRes as $k2 => $v2){
			$supplier = 99;
			if(trim($v2['audit_supplier'])!=""){
				$supplier = $v2['audit_supplier'];
			}
			$arrFinalRes2[$v2['product_code_faulty']][$supplier][] = array($v2['shopcode_faulty'],$v2['date_faulty'],$v2['staff_name_faulty'],$v2['comment_faulty']);
		}
		
		//d($arrFinalRes);
		if($myPart!= null && $mySupplier != null){
			if($mySupplier != 99){
				$detailList = $faulty->listAllDetail($dateBegin, $dateEnd, $mySupplier, $myPart);
			}else{
				$mySupplier = 'null';
				$detailList = $faulty->listAllDetailFromChina($dateBegin, $dateEnd,$mySupplier, $myPart);
			}
			$this->view->myList = $detailList;
			
		}
		$this->view->datebegin = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		$this->view->arrFinalRes = $arrFinalRes;
		$this->view->arrFinalRes2 = $arrFinalRes2;
	}
	/**
	 * this function is summary of damaged  by technician page 
	 * this function is not in good use, need to improve
	 */
	public function physicalDamageSummaryAction(){
		
		// 40003 or faulty Audit = 9;
		$arrShop = unserialize(ARR_SHOP);
		
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		$shop = "";
		
		$faulty = new Model_DbTable_Faultyproduct();
		
		$arrRes = array();
		foreach ($arrShop as $shop){
		
			$list = $faulty->damagedParts($dateBegin, $dateEnd,$shop);
			$arrRes[$shop] = $list;
		}
	
		$this->view->arrRes = $arrRes;
		//d($arrRes);
	}
	
	
}
?>